


//
//  LeeGaoDeViewController.m
//  XiaoHuGaoDe
//
//  Created by 李雪虎 on 2017/8/16.
//  Copyright © 2017年 Leexiaohu. All rights reserved.
//

#import "LeeGaoDeViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#define DefaultLocationTimeout  6
#define DefaultReGeocodeTimeout 3
@interface LeeGaoDeViewController ()<MAMapViewDelegate,AMapLocationManagerDelegate>

@property(nonatomic,strong)NSMutableArray *annotations;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) MAPointAnnotation *pointAnnotaiton;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@property (nonatomic, strong)NSArray *jinweiduArr;
@end

@implementation LeeGaoDeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"附近任务";
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64, width_screen, height_screen-64)];
    _mapView.delegate = self;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
//
    
//    [_mapView addAnnotations:self.annotations];

    
    [self configLocationManager];
    
    
    
    // Do any additional setup after loading the view.
}
- (void)initAnnotations
{
//    self.annotations = [NSMutableArray array];
    
//    CLLocationCoordinate2D coordinates[10] = {
//        {38.092520, 114.336170},
//        {38.092520, 114.336170},
//        {38.098293, 114.352343},
//        {48.004087, 114.348904},
//        {48.001442, 114.353915},
//        {38.089105, 114.353915},
//        {38.089098, 114.360200},
//        {38.098439, 114.360201},
//        {38.079590, 114.324219},
//        {38.078234, 114.352792}};
//    CLLocationCoordinate2DMake(39.989631, 116.481018);
  
    for (int i = 0; i < _jinweiduArr.count; i++)
    {
        MAPointAnnotation *a1 = [[MAPointAnnotation alloc] init];
//        a1.coordinate = coordinates[i];
        a1.coordinate = CLLocationCoordinate2DMake([_jinweiduArr[i][@"latitude"]floatValue], [_jinweiduArr[i][@"longitude"]floatValue]);
        [a1 setTitle:[NSString stringWithFormat:@"%@", _jinweiduArr[i][@"title"]]];
        [a1 setSubtitle:[NSString stringWithFormat:@"%@", _jinweiduArr[i][@"contactName"]]];
//        a1.title      = [NSString stringWithFormat:@"anno: %d", i];
        [_mapView addAnnotation:a1];
    }
    
}
#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}

#pragma mark --gaode
- (void)configLocationManager
{
    //    [AMapServices sharedServices].apiKey =@"06eef37f159d363c63a2250d4b030ba4";
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    // 初始化定位管家并设置代理
    
    // 单次定位
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self initCompleteBlock];
    
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    // 高精度：kCLLocationAccuracyBest，精度很高的一次定位，偏差在10米以内，耗时在10s左右。
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    // 带逆地理（返回坐标和地址信息）。
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    // 获取单次定位信息，第一个参数设置为NO，则不会返回地址信息。
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
    
}
#pragma mark - Initialization

- (void)initCompleteBlock
{
    __weak LeeGaoDeViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        //        else if (error != nil && error.code == AMapLocationErrorRiskOfFakeLocation)
        //        {
        //            //存在虚拟定位的风险：此时location和regeocode没有返回值，不进行annotation的添加
        //            NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.localizedDescription);
        //            return;
        //        }
        //        else
        //        {
        //            //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
        //        }
        
        //修改label显示内容
        if (regeocode)
        {
            NSLog(@"经纬度=====%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
            //            [weakSelf.displayLabel setText:[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
        }
        else
        {
            NSLog(@"经纬度=====%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
             [weakSelf httpUrlditu:[NSString stringWithFormat:@"%f",location.coordinate.longitude] with:[NSString stringWithFormat:@"%f",location.coordinate.latitude]];
            //            [weakSelf.displayLabel setText:[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]];
        }
    };
}
-(void)dealloc{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    [self.mapView removeAnnotations:self.mapView.annotations];
    
}










#pragma mark --附近坐标
-(void)httpUrlditu:(NSString *)longitude with:(NSString *)latitude{
    __weak LeeGaoDeViewController *weakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"task/nearbyTasks.api?access_token="),NSUD_Obj(@"token")];
    [HTTPURL postRequest:url parameters:@{@"longitude":longitude,@"latitude":latitude} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"retFlag"]integerValue]==1) {
            _jinweiduArr = [NSArray array];
            _jinweiduArr =(NSArray *)[PublicTools dictionaryWithJsonString:responseObject[@"data"]];
             [weakSelf initAnnotations];
        }

    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
